#include "repairapplywidget.h"
#include "ui_repairapplywidget.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "loginwidget.h"
#include <QMessageBox>
#include <QDateTime>

RepairApplyWidget::RepairApplyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RepairApplyWidget)
{
    ui->setupUi(this);
}

RepairApplyWidget::~RepairApplyWidget()
{
    delete ui;
}

void RepairApplyWidget::initWindow()
{
    this->setWindowTitle("报修申请");
}

/**
 * @brief 保存
 */
void RepairApplyWidget::on_btn_save_clicked()
{
    QString info = ui->edit_info->toPlainText();
    qDebug() << "报修人：" << LoginWidget::userName
             << "\n报修信息：" << info;
    //插入一条报修记录
    QSqlQuery query;
    query.prepare("INSERT INTO repair_apply (apply_username, apply_info, repair_process) "
                  "VALUES(:apply_username, :apply_info, '待维修')");
    query.bindValue(":apply_username",LoginWidget::userName);
    query.bindValue(":apply_info", info);
    if (!query.exec())
    {
        qDebug() << query.lastError();
    }

    //获取刚插入的报修记录ID
    query.prepare("SELECT id FROM repair_apply ORDER BY id DESC");
    query.exec();
    query.next();
    int record_id= query.value(0).toInt();
    qDebug() << "record_id" << record_id;

    //生成缴费记录
    query.prepare("INSERT INTO pay_record (pay_username, pay_type, is_pay, pay_datetime, record_id) "
                  "VALUES(:pay_username, '维修费', '未缴费', :pay_datetime, :record_id)");
    query.bindValue(":pay_username", LoginWidget::userName);
    query.bindValue(":pay_datetime", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    query.bindValue(":record_id", record_id);
    if (!query.exec())
    {
        qDebug() << query.lastError();
    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("报修申请成功，请等待工作人员维修"));
    }

    emit closeAndFlush();
}

